import {useMorghulisRequest} from "./request";
import {inject, reactive, ref} from "vue";
import type {MorghulisChannel, MorghulisSockets} from "../types/tool/channel.types.ts";
import type {DaoConfig, DaoStatus} from "../types/tool/dao.types.ts";


export function useMorghulisChannel(auth: boolean = false) {
    const {channels} = inject('sockets') as MorghulisSockets
    const {getHttpRequest} = useMorghulisRequest()
    const request = getHttpRequest(auth)
    const URL = ref('')
    const status = reactive<DaoStatus>({loading: false, payload: null})


    function register(
        handler: string,
        channel: MorghulisChannel,
        url?: string
    ) {
        channels[handler] = getChannel(status, channel)
        URL.value = url || `socket/${handler}`
    }

    function activate(body: any) {
        request.post(URL.value, body).then(() => status.loading = true)
    }


    return {register, activate, status}
}

function getChannel(status: DaoStatus, channel?: MorghulisChannel): MorghulisChannel {
    return {
        start: () => {
            status.loading = true
            status.payload = null
            channel?.start && channel.start()
        },
        stop: () => {
            status.loading = false
            status.payload = null
            channel?.stop && channel.stop()
        },
        proceed: (payload) => {
            status.loading = true
            status.payload = payload
            channel?.proceed && channel.proceed(payload)
        }
    }
}